import React from 'react'
import { Form, Input, Modal, Button, Select, message, Row, Col} from 'antd'
import PropTypes from 'prop-types'
import './business.less'
import Uploader from './Uploader'
import API from "../../api/business/business";

const FormItem = Form.Item
// const Search = Input.Search
const Option = Select.Option

// const Search = Input.Search

class IcsComponentsSupplierFilterForm extends React.Component {
    state = {
        audit_status:[
            {value:1, name: '待审核'},
            {value:10, name: '审核通过'},
            {value:20, name: '审核拒绝'}
        ],
        visible: false,
        store_status:[
            {value:'1', name: '开业'},
            {value:'0', name: '未开业'}
        ],
        showStoreViewer: this.props.showStoreViewer,
        options:[],
        optionsProvince:[],
        optionsCity:[],
        optionsArea:[],
        fileList: [],
        isCommit: false,
        city: '',
        district: ''
    }
    componentDidMount () {
        this.getProvince()
    }
    componentWillReceiveProps (nextProps) {
        if ('rowInfo' in nextProps && !this.state.isCommit) {
            if (nextProps.isEditing) {
                this.setState({rowInfo: nextProps.rowInfo})
                if (nextProps.rowInfo.province && nextProps.rowInfo.province !== '0') {
                    this.selectProvince(nextProps.rowInfo.province, nextProps.rowInfo.city, nextProps.rowInfo.district)
                }
                if (nextProps.rowInfo.city && nextProps.rowInfo.city !== '0') {
                    console.log('初始化:' + nextProps.rowInfo.city)
                    this.selectCity(nextProps.rowInfo.city, nextProps.rowInfo.district)
                }
            }
            // 图片
            if (nextProps.rowInfo && nextProps.rowInfo.hasOwnProperty('store_img') && nextProps.rowInfo.store_img && nextProps.rowInfo.store_img.length) {
                let arr = []
                nextProps.rowInfo.store_img.forEach((v, k) => {
                    arr.push({
                        name: v.name,
                        url: v.url,
                        uid: k
                    })
                })
                this.setState({fileList: arr})
            }
        }
        if ('isEditing' in nextProps) {
            if (!nextProps.isEditing) {
                this.setState({rowInfo: false})
            }
        }
    }
    getRegionData = (query) => {
        return API.getRegionList(query).then(res => {
            let newOptions = res.data.listData.map(v => {
                let obj = {
                    value: v.region_id,
                    parent_id: v.parent_id,
                    label: v.region_name,
                    region_type: v.region_type,
                    isLeaf: false
                }
                return obj
            })
            return newOptions
        })
    }
    getProvince = () => {
        this.getRegionData({parent_id: 1}).then(res => {
            this.setState({optionsProvince: res})
        })
    }
    selectProvince = (val,defaultCity, defaultDistrict) => {
        this.setState({isCommit: true}, () => {
            this.getRegionData({parent_id: val}).then(res => {
                this.setState({optionsCity: res, province: val, city: defaultCity && typeof defaultCity !== "object" ? defaultCity : '', district: defaultDistrict ? defaultDistrict: ''})
            })
        })
    }
    selectCity = (val, defaultDistrict) => {
        this.setState({isCommit: true}, () => {
            this.getRegionData({parent_id: val}).then(res => {
                this.setState({optionsArea: res, city: val, district: defaultDistrict && typeof defaultDistrict !== "object" ? defaultDistrict: ''})
            })
        })
    }
    selectArea = (val) => {
        this.setState({district: val})
    }
    handleSearch = (e) => {
        e.preventDefault();
        this.setState({isCommit: true}, () => {
            this.props.form.validateFields((err, values) => {
                if (err) return
                if (this.state.fileList && this.state.fileList.length <= 0) {
                    message.error('请上传门店照片！')
                    return
                }
                if (this.state.fileList && this.state.fileList.length > 0) {
                    values.store_img = this.state.fileList.map(v => {
                        let obj = {
                            name: v.name,
                            url: v.url,
                            uid: v.uid
                        }
                        return obj
                    })
                }
                if (!this.state.city) {
                    message.error('请重新选择城市！')
                    return
                }
                console.log(!this.state.district)
                if (!this.state.district) {
                    message.error('请重新选择区域！')
                    return
                }
                values.shop_id = this.props.shop_id
                if (this.props.isEditing) {
                    values.store_id = this.state.rowInfo.id
                }
                console.log(values)
                if (this.props.isEditing) {
                    this.editData(values)
                } else {
                    this.addData(values)
                }
            });
        })

    }
    onChangeFile = (file) => {
        this.setState({fileList: file})
    }
    addData = (values) => {
        API.addStrore(values).then(res => {
            if (res.error === 0) {
                message.success('添加成功！')
                this.props.doStoreViewer()
                this.props.doSearch()
            } else {
                message.error(res.msg || '添加失败！')
            }
        })
    }
    editData = (values) => {
        API.editStrore(values).then(res => {
            if (res.error === 0) {
                message.success('编辑成功！')
                this.props.doStoreViewer()
                this.props.doSearch()
            } else {
                message.error(res.msg || '编辑失败！')
            }
        })
    }
    onCancel = () => {
        this.setState({isCommit: false})
        this.props.doStoreViewer()
    }

    render () {
        if (JSON.stringify(this.state.rowInfo) === '{}') {
            this.props.form.resetFields()
        }
        const { getFieldDecorator } = this.props.form
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 17 },
            },
        }
        const formItemLayout_r = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 23 },
            },
        }
        return this.props.showStoreViewer && <Modal
            className="store-viewer"
            style={{width: 600}}
            visible={this.props.showStoreViewer}
            title={this.props.isEditing ? "编辑门店" : "添加门店"}
            onCancel={this.onCancel}
        >
            <Form
                layout="inline"
                className="supplier-filter"
                onSubmit={this.handleSearch}>
                <FormItem
                    {...formItemLayout}
                    label="门店名称">
                    {getFieldDecorator('store_name', {
                        rules: [{
                            required: true, message: '请输入门店名称!',
                        }],
                        initialValue: this.state.rowInfo? this.state.rowInfo.store_name : ''
                    })(
                        <Input />
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="联系人">
                    {getFieldDecorator('contact', {
                        rules: [{
                            required: true, message: '请输入联系人!',
                        }],
                        initialValue: this.state.rowInfo? this.state.rowInfo.contact : ''
                    })(
                        <Input />
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="联系电话">
                    {getFieldDecorator('store_tel', {
                        rules: [{
                            required: true, message: '请输入联系电话!'
                        }],
                        initialValue: this.state.rowInfo? this.state.rowInfo.store_tel : ''
                    })(
                        <Input />
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="营业时间">
                    {getFieldDecorator('open_period', {
                        rules: [{
                            required: true, message: '请输入营业时间!'
                        }],
                        initialValue: this.state.rowInfo? this.state.rowInfo.open_period : ''
                    })(
                        <Input />
                    )}
                </FormItem>
                <Row>
                    <Col span={6} style={{color: '#333', textAlign: 'right'}} className="ant-form-item-required">所在区域：</Col>
                    <Col span={17}>
                        <FormItem
                            {...formItemLayout_r}
                            style={{width: '30%', marginRight: '2%'}}
                            label="">
                            {getFieldDecorator('province', {
                                rules: [{
                                    required: true, message: '选择省!',
                                }],
                                initialValue: this.state.rowInfo && this.state.rowInfo.province !== '0' ? this.state.rowInfo.province: ''
                            })(
                                <Select placeholder="请选择" onChange={this.selectProvince}>
                                    {this.state.optionsProvince.map(v =>  <Option key={v.value} value={v.value}>{v.label}</Option>)}
                                </Select>
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout_r}
                            style={{width: '30%', marginRight: '2%'}}
                            label="">
                            {getFieldDecorator('city', {
                                rules: [{
                                    required: true, message: '选择市!',
                                }],
                                initialValue: this.state.rowInfo && this.state.rowInfo.city !== '0' ? this.state.rowInfo.city: ''
                            })(
                                <Select placeholder="请选择" onChange={this.selectCity}>
                                    {this.state.optionsCity.map(v =>  <Option key={v.value} value={v.value}>{v.label}</Option>)}
                                </Select>
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout_r}
                            style={{width: '30%', marginRight: '2%'}}
                            label="">
                            {getFieldDecorator('district', {
                                rules: [{
                                    required: true, message: '选择区!',
                                }],
                                initialValue: this.state.rowInfo && this.state.rowInfo.district !== '0' ? this.state.rowInfo.district: ''
                            })(
                                <Select placeholder="请选择" onChange={this.selectArea}>
                                    {this.state.optionsArea.map(v =>  <Option key={v.value} value={v.value}>{v.label}</Option>)}
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                </Row>
                <FormItem
                    {...formItemLayout}
                    label="详细地址">
                    {getFieldDecorator('address', {
                        rules: [{
                            required: true, message: '请输入详细地址!'
                        }],
                        initialValue: this.state.rowInfo? this.state.rowInfo.address : ''

                    })(
                        <Input />
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="门店经纬度">
                    {getFieldDecorator('jw', {
                        rules: [{
                            required: true, message: '请输入门店经纬度!'
                        }],
                        initialValue: this.state.rowInfo? this.state.rowInfo.jw : ''
                    })(
                        <Input />
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="门店状态">
                    {getFieldDecorator('store_status', {
                        rules: [{
                            required: true, message: '请门店选择状态!'
                        }],
                        initialValue: this.state.rowInfo? this.state.rowInfo.store_status : ''
                    })(
                        <Select style={{ width: 194 }} placeholder="选择状态">
                            {this.state.store_status.map(v =>
                                <Option key={v.value} value={v.value}>{v.name}</Option>
                            )}
                        </Select>
                    )}
                </FormItem>
                <Row style={{height: 'auto'}}>
                    <Col span={6} style={{color: '#333', textAlign: 'right'}} className="ant-form-item-required">上传门店照片：</Col>
                    <Col span={17}>
                        <FormItem
                        >
                            {getFieldDecorator('store_img')(
                                <Uploader fileList={this.state.fileList} onChangeFile={this.onChangeFile}/>
                            )}
                        </FormItem>
                    </Col>
                </Row>

                <div className="btns">
                    <Button type="primary" style={{marginRight: 10}} onClick={this.onCancel}>取消</Button>
                    <Button type="primary" htmlType="submit">提交</Button>

                </div>

            </Form>
        </Modal>
    }
}

IcsComponentsSupplierFilterForm.propTypes = {
    getFieldDecorator: PropTypes.func,
    showStoreViewer: PropTypes.any,
    doSearch: PropTypes.func,
    doStoreViewer: PropTypes.func,
    shop_id: PropTypes.any,
    isEditing: PropTypes.bool,
    rowInfo: PropTypes.object,
    form: PropTypes.object
}

const IcsComponentsSupplierFilter = Form.create()(IcsComponentsSupplierFilterForm)

export default IcsComponentsSupplierFilter
